package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "Filter 0",urlPatterns = {"/*"}/*仅所有资源进行过滤*/)
public class EncodingFilter implements Filter {
    public void destroy(){}
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
        System.out.println("Filter 0 - encoding begins");
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        //获得path
        String path = request.getRequestURI();
        //如果没有字串“/login”，则考虑设置字符编码
        if(!path.contains("/login")){
            //所有资源都要设置响应字符编码
            response.setContentType("application/json;charset=UTF-8");
            //获得请求方法
            String method = request.getMethod();
            //如果是方法是post-put
            if("POST-PUT".contains(method)){
                //设置请求字符集
                request.setCharacterEncoding("UTF8");
            }
        }
        //执行其他过滤器，如过滤器已经执行完毕，则执行原请求
        chain.doFilter(req,res);
        System.out.println("Filter 0 - encoding ends");
    }
}
